package engine.gui;

import java.nio.IntBuffer;

import static org.lwjgl.opengl.GL11.*;

import org.lwjgl.BufferUtils;

public class Scissor {

	private IntBuffer lastScissor;
	private boolean hadScissor;
	
	public Scissor() {
		lastScissor = BufferUtils.createIntBuffer(16);
	}
	
	public void enable(int x, int y, int width, int height) {
		hadScissor = glGetBoolean(GL_SCISSOR_TEST);
		
		if(hadScissor) {
			lastScissor.rewind();
			glGetInteger(GL_SCISSOR_BOX, lastScissor);
			
			width = Math.min(x + width, lastScissor.get(0) + lastScissor.get(2));
			height = Math.min(y + height, lastScissor.get(1) + lastScissor.get(3));
			x = Math.max(x, lastScissor.get(0));
			y = Math.max(y, lastScissor.get(1));
			width -= x;
			height -= y;
		} else {
			glEnable(GL_SCISSOR_TEST);
		}
		
		if(width > 0 && height > 0) {
			glScissor(x, y, width, height);
		}
	}
	
	public void disable() {
		if(hadScissor) {
			glScissor(lastScissor.get(0), lastScissor.get(1), lastScissor.get(2), lastScissor.get(3));
		} else {
			glDisable(GL_SCISSOR_TEST);
		}
	}
}
